<template>
  <!-- 故障处理 -->
  <div class="filterContent">
    <a-form :model="filterForm" layout="inline">
      <a-form-item label="电站">
        <a-select
          v-model:value="filterForm.stationId"
          class="formSelect"
          placeholder="请选择"
          show-search
          optionFilterProp="label"
          style="width: 150px"
          allow-clear
        >
          <a-select-option
            v-for="item in stationNameOptions"
            :key="item.stationId"
            :value="item.stationId"
            :label="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="故障开始日期范围">
        <a-range-picker
          v-model:value="choseTime"
          format="YYYY-MM-DD"
          valueFormat="YYYY-MM-DD"
        />
      </a-form-item>
      <a-form-item label="是否关联工单">
        <a-select
          class="formSelect"
          placeholder="请选择"
          v-model:value="filterForm.relateWorkOrder"
          style="width: 120px"
          allow-clear
        >
          <a-select-option :value="1">是</a-select-option>
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="是否关联操作">
        <a-select
          class="formSelect"
          placeholder="请选择"
          v-model:value="filterForm.relateOperate"
          style="width: 120px"
          allow-clear
        >
          <a-select-option :value="1">是</a-select-option>
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>

      <a-button type="primary" class="filterBtn" @click="searchData"
        >查询</a-button
      >
      <a-button
        v-hasPermission="'FaultHandlingAdd'"
        type="primary"
        class="filterBtn greenBtn"
        @click="handleFault"
        >新增</a-button
      >
      <a-button
        type="primary"
        class="filterBtn greenpPlainBtn"
        @click="handleFaultModal"
        >导入</a-button
      >
      <a-button type="primary" class="filterBtn yellowBtn" @click="handleExport"
        >导出</a-button
      >
    </a-form>
  </div>
  <div class="tableContent" ref="tableContainerRef">
    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      :scroll="tableScroll"
      :pagination="false"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'relateWorkOrderCode'">
          <a-button
            type="link"
            @click="goWorkOrder(record)"
            v-if="record?.relateWorkOrderCode"
            >{{ record.relateWorkOrderCode }}</a-button
          >
        </template>
        <template v-if="column.dataIndex === 'relateOperateCodeList'">
          <a-button
            type="link"
            @click="goOperationRecord(item)"
            v-for="(item, idx) in record.relateOperateCodeList"
            :key="idx"
            >{{ item }}</a-button
          >
        </template>
        <template v-if="column.dataIndex === 'handle'">
          <a-button type="link" @click="handleEdit(record)">编辑</a-button>
          <a-button type="link" @click="handleWorkOrder(record)"
            >关联工单</a-button
          >
          <a-button type="link" @click="handleOperate(record)"
            >关联操作</a-button
          >

          <a-popconfirm
            title="确定删除该记录吗？"
            @confirm="handleDelete(record)"
            ok-text="确定"
            cancel-text="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="filterForm.current"
      v-model:page-size="filterForm.size"
      :total="total"
      position="bottomRight"
      show-size-changer
      @change="getFaultDealPage"
      :show-total="(total) => `总共 ${total} 条`"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>
  </div>
  <!-- 新增故障处理-->
  <addFault
    :addFaultVisible="addFaultVisible"
    :isEdit="isEdit"
    :rowData="rowData"
    :stationList="stationNameOptions"
    :planShutdown="planShutdown"
    @update:addFaultVisible="addFaultVisible = $event"
    @refresh="searchData"
  />
  <!-- 导入 -->
  <FaultModal
    :visible="faultModal"
    :planShutdown="planShutdown"
    @update:visible="(val) => (faultModal = val)"
    @getFaultDealPage="getFaultDealPage"
  />
  <!-- 关联操作弹窗 -->
  <OperateModal
    :visible="operateVisible"
    :rowData="operateData"
    @refresh="searchData"
    @update:visible="(val) => (operateVisible = val)"
  />
  <!-- 关联工单弹窗 -->
  <RelateWorkOrder
    v-model:visible="relateWorkOrderVisible"
    :relateWorkOrderCode="currentRecord?.relateWorkOrderCode"
    :rowData="currentRecord"
    @refresh="searchData"
  />
</template>
<script setup>

import useTableScroll from "@/hooks/useTableScroll"
import addFault from "./conpoments/addFault.vue"
import FaultModal from "./conpoments/faultModal.vue"
import OperateModal from "./conpoments/OperateModal.vue"
import RelateWorkOrder from "./conpoments/RelateWorkOrder.vue"

import utilsExportFile from "@/utils/exportFile"
const tableLoading = ref(false)
const route = useRoute()
const router = useRouter()
const $api = inject("$api")
const tableData = ref([])
const choseTime = ref([])
const total = ref()
const planShutdown = ref(0)
const filterForm = ref({
  stationId: null,

  relatedWorkOrder: null,
  size: 20,
  current: 1,
})
const columns = ref([
  {
    title: "故障编号",
    dataIndex: "faultCode",
    key: "faultCode",
    width: 150,
    align: "center",
  },
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 160,
    align: "center",
  },
  {
    title: "设备所属厂商",
    dataIndex: "supplierName",
    key: "supplierName",
    width: 120,
    align: "center",
  },
  {
    title: "所属省份",
    dataIndex: "provName",
    key: "provName",
    width: 120,
    align: "center",
  },
  {
    title: "上月设备效率",
    dataIndex: "lastMonthEfficiently",
    key: "lastMonthEfficiently",
    width: 120,
    align: "center",
  },
  {
    title: "故障现象描述",
    dataIndex: "faultDesc",
    key: "faultDesc",
    width: 220,
    align: "center",
  },
  {
    title: "缺陷及故障处理方法描述",
    dataIndex: "faultDealDesc",
    key: "faultDealDesc",
    width: 220,
    align: "center",
  },
  {
    title: "故障类别",
    dataIndex: "faultTypeName",
    key: "faultTypeName",
    width: 120,
    align: "center",
  },
  {
    title: "故障细分",
    dataIndex: "faultSegmentName",
    key: "faultSegmentName",
    width: 120,
    align: "center",
  },
  {
    title: "故障归属",
    dataIndex: "faultBelongName",
    key: "faultBelongName",
    width: 120,
    align: "center",
  },
  {
    title: "故障开始时间",
    dataIndex: "faultStartDate",
    key: "faultStartDate",
    width: 120,
    align: "center",
  },
  {
    title: "电池柜容量(kWh)",
    dataIndex: "linkCap",
    key: "linkCap",
    width: 120,
    align: "center",
  },
  {
    title: "故障电池柜个数",
    dataIndex: "faultLinkNum",
    key: "faultLinkNum",
    width: 120,
    align: "center",
  },
  {
    title: "故障对接人",
    dataIndex: "faultContactPerson",
    key: "faultContactPerson",
    width: 120,
    align: "center",
  },
  {
    title: "是否为计划停机",
    dataIndex: "planShutdownStr",
    key: "planShutdownStr",
    width: 80,
    align: "center",
  },
  {
    title: "是否导致项目停运",
    dataIndex: "causeProjectShutdownStr",
    key: "causeProjectShutdownStr",
    width: 80,
    align: "center",
  },
  {
    title: "影响充放次数",
    dataIndex: "affectNum",
    key: "affectNum",
    width: 120,
    align: "center",
  },
  {
    title: "故障结束时间",
    dataIndex: "faultEndDate",
    key: "faultEndDate",
    width: 120,
    align: "center",
  },
  {
    title: "计划解决时间",
    dataIndex: "planResolveDate",
    key: "planResolveDate",
    width: 120,
    align: "center",
  },
  {
    title: "实际解决时间",
    dataIndex: "actualResolveDate",
    key: "actualResolveDate",
    width: 120,
    align: "center",
  },
  {
    title: "关联工单编号",
    dataIndex: "relateWorkOrderCode",
    key: "relateWorkOrderCode",
    width: 120,
    align: "center",
  },
  {
    title: "关联操作编号",
    dataIndex: "relateOperateCodeList",
    key: "relateOperateCodeList",
    width: 120,
    align: "center",
  },
  {
    title: "故障修复时间（小时）",
    dataIndex: "faultFixTime",
    key: "faultFixTime",
    width: 120,
    align: "center",
  },
  {
    title: "故障影响收益（元）",
    dataIndex: "faultAffectIncome",
    key: "faultAffectIncome",
    width: 120,
    align: "center",
  },
  {
    title: "总结建议描述",
    dataIndex: "summaryDesc",
    key: "summaryDesc",
    width: 120,
    align: "center",
  },
  {
    title: "填写人",
    dataIndex: "createUserName",
    key: "createUserName",
    width: 120,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 260,
    align: "center",
    fixed: "right",
  },
])
onMounted(async () => {
  // handleSearchStationName();
  // getFaultDealPage();
})
//获取电站列表
const stationNameOptions = ref([])
const handleSearchStationName = async () => {
  const res = await $api.companyStationtList()
  stationNameOptions.value = res.data
  await nextTick()
}
//导出
const handleExport = async () => {
  const res = await $api.faultDealExportData(filterForm.value)
  utilsExportFile.exportFile(res, `故障处理.xlsx`)
}
//查询
const searchData = async () => {
  filterForm.value.current = 1
  if (choseTime.value && choseTime.value.length > 0) {
    filterForm.value.faultStartDate = `${choseTime.value[0]} 00:00:00`
    filterForm.value.faultEndDate = `${choseTime.value[1]} 23:59:59`
  } else {
    filterForm.value.faultStartDate = ""
    filterForm.value.faultEndDate = ""
  }
  getFaultDealPage()
}
//导入故障
const faultModal = ref(false)
const handleFaultModal = () => {
  faultModal.value = true
}
//获取分页
/**
 * @param {planShutdown}
 * 通过planShutdown字段区分 非计划停运 和 计划停运
 * 0:非计划停运
 * 1:计划停运
 */
const getFaultDealPage = async () => {
  tableLoading.value = true
  filterForm.value.planShutdown = planShutdown.value
  const res = await $api.faultDealPage(filterForm.value)
  if (res && res.code === 0) {
    // 将逗号分隔的relateOperateCode转为数组
    const records = res.data.records.map((item) => {
      if (
        item.relateOperateCode &&
        typeof item.relateOperateCode === "string"
      ) {
        item.relateOperateCodeList = item.relateOperateCode
          .split(",")
          .filter((code) => code.trim() !== "")
      } else {
        item.relateOperateCodeList = []
      }
      return item
    })
    tableData.value = records
    total.value = res.data.total
  }
  tableLoading.value = false
}
//跳转工单
const goWorkOrder = (record) => {
  router.push({
    path: "/Operation/WorkOrder/Error",
    query: {
      workOrderCode: record.relateWorkOrderCode,
    },
  })
}
//跳转操作
const goOperationRecord = (record) => {
  router.push({
    path: "/DigitalAnalysis/FaultRegistration/OperationRecord",
    query: {
      operateCode: record,
    },
  })
}
//新增故障
const addFaultVisible = ref(false)
const handleFault = () => {
  isEdit.value = false
  addFaultVisible.value = true
}
//删除
const handleDelete = async (record) => {
  let res = await $api.faultDealDel(record.id)
  if (res && res.code === 0) {
    searchData()
    message.success("操作成功")
  }
}
//编辑
const rowData = ref({})
const isEdit = ref(false)
const handleEdit = (record) => {
  rowData.value = record
  isEdit.value = true
  addFaultVisible.value = true
}
//关联操作
const operateVisible = ref(false)
const operateData = ref({})
const handleOperate = (record) => {
  operateVisible.value = true
  operateData.value = record
}
//关联工单

const tableContainerRef = ref(null)
const { tableScroll } = useTableScroll(tableData, tableContainerRef, 100)
const relateWorkOrderVisible = ref(false)
const currentRecord = ref(null)

const handleWorkOrder = (record) => {
  currentRecord.value = record
  relateWorkOrderVisible.value = true
}

const handleSaveWorkOrder = (workOrderCode) => {
  // 这里处理保存关联工单的逻辑
  console.log("保存关联工单:", workOrderCode)
}

watch(
  () => route.path,
  (newPath, oldPath) => {
    const url = [
      "/DigitalAnalysis/Unplanned/UnplannedFaultHandling",
      "/DigitalAnalysis/Planned/PlannedFaultHandling",
    ]
    if (url.includes(newPath)) {
      const matchPlanShutdown = {
        "/DigitalAnalysis/Unplanned/UnplannedFaultHandling": 0,
        "/DigitalAnalysis/Planned/PlannedFaultHandling": 1,
      }
      planShutdown.value = matchPlanShutdown[newPath]
      console.log("进入页面")
      handleSearchStationName()
      getFaultDealPage()
    } else if (url.includes(oldPath)) {
      console.log("离开页面")
    }
  },
  { immediate: true }
)
</script>
<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.formInput {
  width: 155px;
}
.filterBtn {
  margin: 0 10px 0 0;
  &:last-child {
    margin-right: 0;
  }
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
</style>
